<template>
  <div class="bcRhide">
    <div class="fulltext" v-if='isReading'>
      <div class="fullName">
        <h1 class="elips">{{readingItem.MTitle}}</h1>
        <button class="fullread" @click="cnkiReadFullScreen">全屏阅读</button>
        <a class="Reback" @click="goBack">返回</a>
      </div>
      <div class="fullcon school-read-online"
           :style="{height: containerHeight + 'px', overflow: isShowType != 'richtext' ? 'hidden' : 'auto'}">
        <!--富文本类型-->
        <div v-html='readingItem.Content' v-if="isShowType==='richtext'"></div>
        <!--文档类型-->
        <iframe :src="readingItem.onlyOfficeSrc" v-if=" isShowType === 'onlyOffice'"
                frameborder="0" scrolling="no" allowfullscreen></iframe>
        <!--腾讯云视频-->
        <iframe :src="readingItem.tencentSrc" v-if=" isShowType === 'tencentVideo'"
                frameborder="0" scrolling="no" allowfullscreen></iframe>
        <!--原生视频类-->
        <video preload="none" controls="controls" :poster="videoPoster"
               :src="readingItem.Uri"
               v-if="isShowType === 'nativeVideo'" style="max-width: 100%; max-height: 100%;"></video>
        <!--音频-->
        <audio :src="readingItem.Uri" controls="controls" preload="none"
               v-if="isShowType === 'audio'"></audio>
        <!--图片-->
        <img v-if="isShowType === 'image'"
             :src="readingItem.Uri"
             :alt="readingItem.MTitle">
      </div>
    </div>
    <div class="" id="bxzylist" v-show='!isReading'>
      <div class="schoolFilter">
        <div class="searchContent">
          <span>
            <input type="text" placeholder="输入课程名/章节名/资源名/提交人搜索" v-model.trim="searchContent"
                   @keyup.enter="doSearch(true)" maxlength="50"/>
            <ins v-show="showClearContentBtn" @click="clearContent"></ins>
          </span>
          <button @click="doSearch(true)">搜索</button>
        </div>
        <div class="filter01">
          <span :class="{active: chooseType === 'all'}" @click="changeChooseType('all')">全部</span>
          <span v-for="item, index in arrTypes" :class="{active: chooseType === item.key}"
                @click="changeChooseType(item.key)">{{item.name}}</span>
        </div>
        <div class="filter02">
          <span>
            <label>
              <input type="checkbox" name="name" v-model="onlyThisCourse"/>
              仅看本课程
            </label>
          </span>
          <span>
            <label>
              <input type="checkbox" name="name" v-model="onlyThisSection"/>
              仅看本小节
            </label>
          </span>
        </div>
      </div>

      <div class="cnkiSort">
        <span class="fl" v-show='showAdd && list.length > 0'>
          <ins :class="{mchecked: !allChecked, mcheck: allChecked}"
               @click="allChecked = !allChecked"></ins>全选
        </span>
        <span class="cnfolder" v-show='showAdd && list.length > 0' @click="addSchoolData">添加到课程</span>
        <div class="xbSort"> 排序：
          <span class="activeB" v-show="false"> 相关度</span>
          <span v-show="orderType === 1" class="activeT" @click=""> 时间</span>
          <span v-show="orderType === 0" class="activeB" @click=""> 时间</span>
          <span class="fr cnkitotal">共
            <em class="orange">{{total}}</em>条
          </span>
        </div>
      </div>
      <div class="cnkibox" v-loading="loadWhenSearch" element-loading-background="#fff">
        <!-- 没有搜索时显示  begin -->
        <div class="cnkinodata" v-show='firstTime'>
          <b class="orange">提示：</b>
          <p>您可以检索查阅知网专业论文、教学案例、教学资源等，</p>
          <p>也可将这些资源添加到您的资料中，用于教学或研究。</p>
        </div>
        <div class="cnkinodata" v-show="list.length === 0 && !firstTime">
          <b class="orange">提示：</b>
          <p>没有符合条件的资源!</p>
        </div>
        <!-- 没有搜索时显示  end -->
        <!-- line -->
        <dl class="cnkiList" v-for='(item,index) in list'>
          <dt class="blue">
            <span class="checkbtn" v-show='showAdd'>
              <ins :class="{mcheck: item._isChecked, mchecked: !item._isChecked}"
                   @click="item._isChecked = !item._isChecked"></ins>
            </span>
            <p @click="curItemIndex = index">{{item.Title}}</p>
          </dt>
          <dd class="author" @click="curItemIndex = index">
            <p class="cnkitop">
              <span class="dipgray marR10">提交人：{{item.RealName}} </span>
              <span class="dipgray"> 提交时间：{{item.CreateTime | dateFilter}}</span>
            </p>
          </dd>
          <dd class="cnkiSumary" v-show='curItemIndex === index'>
            <p>所属课程：{{item.CourseVersion}} {{item.CourseName}} {{item.SubjectName || ''}}</p>
            <p>所属课程目录：{{item.CatalogName}}</p>
            <p class="sumbot">
              <span class=" fl">资源类型：{{item._resourceTypeText}}</span>
              <span class="fr">
                <a class="cnkiread" href="javascript:;" @click="watchOnline(item)">查看</a>
                <a class="cnkidown" href="javascript:;"
                   v-if="item._showDownLoadBtn"
                   :class="{'not-allowed': !item._allowDownLoad}" @click="downloadItem(item)" title="下载">下载</a>
              </span>
            </p>
          </dd>
        </dl>
        <div style="text-align: center;" v-show="total > pageSize">
          <el-pagination @current-change="searchList(true)" :current-page.sync="pageIndex"
                         :page-size="pageSize" layout="prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {mapActions} from 'vuex';
  import {getTencentIfrSrc} from "../../../core/util";

  export default {
    props: {
      showAdd: {
        type: Boolean,
        default: false
      },
      containerHeight: {
        type: Number
      },
      courseClassId: {
        type: String,
        default: ""
      }
    },
    data() {
      return {
        sourceLib: 'PbEdu',
        prefix: globalVar.cnkiFullTextAddr,
        searchContent: "",
        chooseType: 'all', // 检索时选择的资源类型
        arrTypes: [], // 检索资源类型的数组
        objTypes: {}, // 检索资源类型的对象，由数组改变而来
        onlyThisCourse: true, // 只看本课程
        onlyThisSection: true, // 只看本小结
        pageIndex: 1,
        pageSize: 6,
        orderType: 0,
        list: [],
        total: 0,
        curItemIndex: null,
        isReading: false,
        isShowType: '', // 当前阅读的类型
        videoPoster: `${globalVar.SITEORIGIN}Editor/images/videoDefaultImg.jpg`,
        showTencetnSrc: "", // 腾讯云播放地址
        readingItem: {},
        loadWhenSearch: false, // 搜索时的loading层
        firstTime: true, // 首次进入页面
        allChecked: false, // 是否全选
      };
    },
    filters: {
      dateFilter(str) {
        return str.substr(0, 10);
      }
    },
    computed: {
      showClearContentBtn() {
        return !!this.searchContent;
      }
    },
    watch: {
      // 切换搜索的资源类型
      chooseType(newVal, oldVal) {
        this.doSearch();
      },
      // 只看本课程
      onlyThisCourse(newVal, oldVal) {
        this.doSearch();
      },
      // 只看本小节
      onlyThisSection(newVal, oldVal) {
        this.doSearch();
      },
      /**
       * 全选的变化
       */
      allChecked(newvalue, oldvalue) {
        this.toggleAllCheck(newvalue);
      }
    },
    methods: {
      ...mapActions(['addStatistics']),
      /**
       * 获取url地址，测试环境避开跨域头验证
       * @param url
       * @return {*}
       */
      getUrl(url) {
        if (process.env.NODE_ENV === "development") {// 开发阶段绕过限制
          return `/corsWithHeader${url}`;
        } else {
          return this.prefix + url;
        }
      },
      /**
       * 获取检索的配置文件，全部，富文本，文档...
       */
      GetOpenCourseConfig() {
        axios.get(this.getUrl("/Api/Search/config/PbEdu"), {
          headers: {
            'token': dataFromFather.token
          }
        }).then(res => {
          if (res && res.data && res.data.Code == 200) {
            this.arrTypes = res.data.Data.extTypeConfig || [];
            for (let item of this.arrTypes) {
              this.objTypes[item.key] = item.name;
            }
          } else {
            this.globalShowMsg({msg: "获取本校资源配置出错！", type: "warning"});
          }
        }).catch(err => {
          console.log(err);
          this.globalShowMsg({msg: "获取本校资源配置出错！", type: "warning"});
        })
      },
      /**
       * 切换类型搜索
       */
      changeChooseType(type) {
        if (this.chooseType === type) return;
        this.chooseType = type;
      },
      /**
       * 搜索前调用的方法方法
       * @param byUser 是不是用户触发的
       */
      doSearch(byUser) {
        if (this.searchContent) {
          if (this.firstTime) this.firstTime = false;
          // 确认当前的pageIndex
          if (this.pageIndex != 1) {
            return this.pageIndex = 1;
          }
          this.searchList();
        } else {
          if (byUser === true) this.globalShowMsg({msg: "检索词不能为空！", type: "warning"});
        }
      },
      /**
       * 检索的主方法
       * @param manualPage 手动分页
       */
      searchList(manualPage) {
        if (manualPage === true && !this.searchContent) { // 手动分页还需要确认一次搜索框有值
          return this.globalShowMsg({msg: "检索词不能为空！", type: "warning"});
        }

        this.loadWhenSearch = true;
        axios.get(this.getUrl("/api/Search/query"), {
          params: this.getQueryParams(),
          headers: {
            'token': dataFromFather.token
          }
        }).then(res => {
          if (res && res.data && res.data.Code === 200) {
            let data = res.data.Data;
            this.total = data.Count;
            this.list = this.processRawData(data.Rows);
            this.curItemIndex = null;
          } else {
            console.log(res);
            this.globalShowMsg({msg: "检索出错", type: 'warning'});
          }
          this.loadWhenSearch = false;
        }).catch(err => {
          console.log(err);
          this.loadWhenSearch = false;
          this.globalShowMsg({msg: "检索出错", type: 'warning'});
        });
        if (this.pageIndex === 1) {
          this.addStatistics(33);
        }
      },
      /**
       * 获取检索方法的参数
       */
      getQueryParams() {
        // true是精确查找 false是模糊查找
        let arrParams = []
          , originalObj = {
          userId: dataFromFather.userID,
          source: this.sourceLib,
          pageSize: this.pageSize,
          pageIndex: this.pageIndex,
          sortKey: 'date',
          key1: `query|${this.searchContent}|false`
        };
        if (this.chooseType != "all") { // 选择了资源类型
          arrParams.push(`AND|resourcetype|${this.chooseType}|true`);
        }
        if (this.onlyThisCourse === true) { // 选中了只看本课程
          arrParams.push(`AND|coursecode|${dataFromFather.courseCode}|true`);
        }
        if (this.onlyThisSection === true) { // 选中了只看本小节
          arrParams.push(`AND|catalogcode|${dataFromFather.catalogCode}|true`);
        }
        arrParams.forEach((item, index, arr) => {
          let key = "key" + (index + 2);
          originalObj[key] = item;
        });
        return originalObj;
      },
      /**
       * 清除搜索框内容
       */
      clearContent() {
        this.searchContent = "";
      },
      /**
       * 处理检索接口返回的数据
       */
      processRawData(arr) {
        arr = arr || [];
        let resArr = [];
        // 处理资源数组
        for (let item of arr) {
          // todo 操作raw返回更好用的
          item._resourceTypeText = this.objTypes[item.ResourceType] || '其他'; // 资源类型
          item._isChecked = this.allChecked === true;
          // 是否展示下载按钮
          item._showDownLoadBtn = !(item.ResourceType === "richtext" || item.ResourceType === "video" || item.ResourceType === "thirdparty");
          item._allowDownLoad = item.IsDownLoad === 1;
          resArr.push(item);
        }
        return resArr;
      },
      /**
       * 切换全选
       */
      toggleAllCheck(flag) {
        for (let item of this.list) {
          item._isChecked = flag;
        }
      },
      goBack() {
        this.isReading = false;
      },
      /**
       * 在线阅读视频和office
       * @param item
       */
      watchOnline(item) {
        let fileType = item.ResourceType;
        this.isShowType = "";
        axios.get(this.getUrl("/help/PbEdu/fulltext?dbCode=PbEdu&mcode=" + item.MCode), {
          headers: {
            token: dataFromFather.token
          }
        }).then(res => {
          if (res && res.data && res.data.Code === 200) {
            let data = res.data.Data;
            console.log(data);
            if (fileType === "thirdparty" && data.platformid === 2) {
              // 知网资源
              return window.open(data.Uri, "_blank");
            }
            this.isReading = true;
            switch (fileType) {
              case "richtext":
                this.isShowType = "richtext";
                this.readingItem = data;
                if(!data.Content){
                  this.globalShowMsg({msg: "当前资源没有内容！", type: "warning"});
                }
                // 富文本
                break;
              case "video":
                // 视频
                if (data.Platformid === 1) {
                  // 腾讯云视频
                  this.isShowType = "tencentVideo";
                  this.readingItem = {
                    ...data,
                    tencentSrc: getTencentIfrSrc(data.FileCode)
                  }
                } else {
                  // 非腾讯云视频
                  this.isShowType = "nativeVideo";
                  this.readingItem = data;
                }
                break;
              case "audio":
                // 音频
                this.isShowType = "audio";
                this.readingItem = data;
                break;
              case "image":
                // 图片
                this.isShowType = "image";
                this.readingItem = data;
                break;
              case "wordprocessing":
              case "presentation":
              default:
                // 文档
                // PPT
                this.getOnlyOfficeSrc({
                  fileCode: data.FileCode,
                  fileName: data.MTitle,
                  userId: item.UserId,
                  userName: item.UserName
                }).then(res => {
                  if (res && res.data && res.data.Code === 200) {
                    this.isShowType = "onlyOffice";
                    let type = "embedded";
                    if (data.Extension.toLowerCase().indexOf("ppt") >= 0) {
                      type = "desktop";
                    }
                    this.readingItem = {
                      ...data,
                      onlyOfficeSrc: res.data.Data.Uri + "&Type=" + type + "&version=" + Math.random().toFixed(5)
                    };
                  } else {
                    this.globalShowMsg({msg: "请求onlyoffice地址出错", type: "warning"});
                  }
                }).catch(err => {
                  console.log(err);
                  this.globalShowMsg({msg: "请求onlyoffice地址出错", type: "warning"});
                });
                break;
            }
          } else {
            this.globalShowMsg({msg: "获取全文接口出错！", type: "warning"});
          }
        }).catch(err => {
          console.log(err);
          this.globalShowMsg({msg: "获取全文接口出错！", type: "warning"});
        });
        this.addStatistics(33); // 阅读本校资源
      },
      /**
       * 获取onlyoffice地址
       * @param dataset
       */
      getOnlyOfficeSrc(dataset) {
        return axios.get(globalVar.onlyOffice + `/api/editor/initget`, {
          params: dataset,
          headers: {
            token: dataFromFather.token
          }
        });
      },
      /**
       * 下载资源
       */
      downloadItem(item) {
        if (!item._allowDownLoad) return;
        axios.get(this.getUrl("/help/PbEdu/fulltext?dbCode=PbEdu&mcode=" + item.MCode), {
          headers: {
            token: dataFromFather.token
          }
        }).then(res => {
          if (res && res.data && res.data.Code === 200) {
            // let ifr = document.createElement("iframe");
            // ifr.style.display = "none";
            // document.body.appendChild(ifr);
            // ifr.src = res.data.Data.Uri;
            window.open(res.data.Data.Uri, "_blank");
          } else {
            this.globalShowMsg({msg: "获取全文接口出错！", type: "warning"});
          }
        }).catch(err => {
          console.log(err);
          this.globalShowMsg({msg: "获取全文接口出错！", type: "warning"});
        });
      },
      // 全屏阅读
      cnkiReadFullScreen() {
        let that = this;
        const layer = layui.layer;
        let w = $(window).width();
        let h = $(window).height();
        if(that.isShowType == "richtext"){
          return layer.open({
            type: 1,
            title: that.readingItem.MTitle,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: that.readingItem.Content
          });
        }
        if(that.isShowType == "image"){
          // 图片的普通全屏打开方式
          return layer.open({
            type: 1,
            title: that.readingItem.MTitle,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: '<img src="' + that.readingItem.Uri + '" style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);max-width: initial;">'
          });
        }
        if(that.isShowType == "audio"){
          return layer.open({
            type: 1,
            title: that.readingItem.MTitle,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: '<audio src="' + that.readingItem.Uri + '" controls="controls" preload="none" style="display: block;margin:0 auto;"></audio>'
          });
        }
        if(that.isShowType == "nativeVideo"){
          return layer.open({
            type: 1,
            title: that.readingItem.MTitle,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: '<video src="' + that.readingItem.Uri + '" controls="controls" preload="none" style="display: block;margin:0 auto;max-width: 100%;max-height:100%;"></video>'
          });
        }
        layer.open({
          type: 2,
          title: that.readingItem.MTitle,
          shade: false,
          maxmin: true, //开启最大化最小化按钮
          area: ['1000px', 0.9 * h + 'px'],
          content: that.readingItem.tencentSrc || that.readingItem.onlyOfficeSrc
        });
      },
      /**
       * 添加到编辑器
       */
      addSchoolData() {
        let tempArr = [], finalArr = [];
        for (let item of this.list) {
          if(item._isChecked){
            tempArr.push(item);
          }
        }
        if(tempArr.length === 0) return this.globalShowMsg({msg: "请选择要添加的资源！", type: "warning"});
        let loading = this.$loading({
          lock: true,
          text: '添加中，请稍后...'
        });
        for (let item of tempArr) {
          let fileType = item.ResourceType;
          axios.get(this.getUrl("/help/PbEdu/fulltext?dbCode=PbEdu&mcode=" + item.MCode), {
            headers: {
              token: dataFromFather.token
            }
          }).then(res => {
            if (res && res.data && res.data.Code === 200) {
              let data = res.data.Data;
              // console.log(data);
              switch (fileType) {
                case "thirdparty":
                  // 知网资源
                  if(data.platformid === 2){
                    finalArr.push({
                      type: "cnkiLink",
                      name: data.MTitle,
                      src: data.Uri
                    });
                  }
                  break;
                case "richtext":
                  // 富文本
                  finalArr.push({
                    type: "richtext",
                    name: data.MTitle,
                    ifrSrc: data.Uri,
                    iconType: "richtext"
                  });
                  break;
                case "video":
                  // 视频
                  if (data.Platformid === 1) {
                    // 腾讯云视频
                    finalArr.push({
                      type: "video",
                      name: data.MTitle,
                      ifrSrc: getTencentIfrSrc(data.FileCode),
                      resourceID: data.FileCode
                    });
                  } else {
                    // 非腾讯云视频
                    finalArr.push({
                      type: "nativevideo",
                      name: data.MTitle,
                      src: data.Uri
                    });
                  }
                  break;
                case "audio":
                  // 音频
                  finalArr.push({
                    type: "nativeaudio",
                    name: data.MTitle,
                    src: data.Uri
                  });
                  break;
                case "image":
                  // 图片
                  finalArr.push({
                    type: "justImg",
                    name: data.MTitle,
                    src: data.Uri
                  });
                  break;
                case "wordprocessing":
                case "presentation":
                default:
                  // 文档
                  // PPT
                  this.getOnlyOfficeSrc({
                    fileCode: data.FileCode,
                    fileName: data.MTitle,
                    userId: item.UserId,
                    userName: item.UserName
                  }).then(result => {
                    if (result && result.data && result.data.Code === 200) {
                      let type = "embedded";
                      if (data.Extension.toLowerCase().indexOf("ppt") >= 0) {
                        type = "desktop";
                      }
                      finalArr.push({
                        type: "onlyoffice",
                        name: data.MTitle,
                        ifrSrc: result.data.Data.Uri + "&Type=" + type + "&version=" + Math.random().toFixed(5),
                        resourceID: data.FileCode,
                        iconType: "office_" + data.Extension.toLowerCase().substr(0, 3)
                      });
                      if(finalArr.length === tempArr.length){
                        // 遍历完成
                        this.addSchoolDataDone(finalArr, loading);
                      }
                    } else {
                      this.globalShowMsg({msg: "请求onlyoffice地址出错", type: "warning"});
                      loading.close();
                    }
                  }).catch(err => {
                    console.log(err);
                    this.globalShowMsg({msg: "请求onlyoffice地址出错", type: "warning"});
                    loading.close();
                  });
                  break;
              }
              if(finalArr.length === tempArr.length){
                // 遍历完成
                this.addSchoolDataDone(finalArr, loading);
              }
            } else {
              this.globalShowMsg({msg: "获取全文接口出错！", type: "warning"});
            }
          }).catch(err => {
            console.log(err);
            this.globalShowMsg({msg: "获取全文接口出错！", type: "warning"});
          })
        }
      },
      /**
       * 数据处理完毕后添加到编辑器
       * @param arr 最终要添加到编辑器中的数组
       * @param loading loading instance
       */
      addSchoolDataDone(arr, loading){
        this.clearAllCheck();
        this.toggleAllCheck(false);
        this.$emit('add-school-data', arr);
        this.addStatistics(34); // 添加本校资源
        loading.close();
      },
      /**
       * 清除全选的状态
       */
      clearAllCheck(){
        this.allChecked = false;
      },
    },
    created() {
      if (this.courseClassId) {
        let interval = setInterval(() => {
          if (Object.prototype.toString.call(window.dataFromFather) === '[object Object]') {
            // 父页面完成传值
            clearInterval(interval);
            this.GetOpenCourseConfig();
          }
        }, 1000);
      }
    },
  };
</script>

<style scoped>
  .school-read-online {
    margin: 0;
    width: 100%;
  }

  label {
    cursor: pointer;
  }

  .cnfolder {
    border: 1px solid #bad5e9;
    display: inline-block;
    height: 22px;
    line-height: 22px;
    color: #2a8cd7;
    padding: 0px 8px;
    margin-left: 5px;
  }

  .cnfolder:hover {
    border: 1px solid #00a4e6;
    cursor: pointer;
    background-color: #e5faff;
  }

  .schoolFilter .searchContent span input {
    vertical-align: top;
  }

  .cnkiSort {
    margin-left: 5px;
  }

  video {
    max-height: 100%;
    max-width: 100%;
  }

  .cnkidown {
    font-size: 12px;
    line-height: 24px;
    background: url(../../../assets/images/cnkisoure.png) no-repeat 0px -156px;
    display: inline-block;
    padding-left: 20px;
    margin: 0px 3px;
    cursor: pointer;
  }

  .not-allowed {
    color: #C9C9C9;
    cursor: not-allowed;
  }
</style>
